//
//  RestoreAudioList.swift
//  GhostWorld
//
//  Created by Kam on 2018/5/25.
//  Copyright © 2018 LKGood. All rights reserved.
//

import Foundation
import CoreData

private let entityName = CoreDataEntityName.restoreAudioList.rawValue
private let context = CoreDataHelper.getContext()

enum RestoreAudioListType: Int16 {
  case unknown = 0
  case album = 1
  case downloaded = 2
  case playlist = 3
  case fav = 4
  case playHistory = 5
}

extension RestoreAudioList {
  func getAudios() -> [Audio]? {
    if let audioIDs = self.audioIDs {
      var audios = [Audio]()
      audioIDs.components(separatedBy: ",").forEach {
        if let audio = EntityManager.fetch(Audio.self, fetchType: .id(Int($0)!)) {
          audios.append(contentsOf: audio)
        }
      }
      return audios
    } else {
      return nil
    }
  }
}

extension RestoreAudioList {
  static func get() -> RestoreAudioList? {
    let request = NSFetchRequest<RestoreAudioList>()
    let entity = NSEntityDescription.entity(forEntityName: entityName, in: context)
    request.entity = entity
    if let currentUser = UserManager.shared.currentUser {
      request.predicate = NSPredicate(format: "userID = \(currentUser.identifier)")
    } else {
      request.predicate = NSPredicate(format: "userID = \(-1)")
    }
    do {
      if let restoreAudioList = try context.fetch(request).first {
        return restoreAudioList
      } else {
        return nil
      }
    } catch let error {
      loggingPrint(error)
      return nil
    }
  }
  
  static func update(nowPlayingAlbumID: Int, nowPlayingAudioID: Int, audios: [Audio]?, refID: String?, name: String?, type: RestoreAudioListType) throws {
    do {
      // remove current list
      try remove()
    } catch let error {
      throw error
    }
    
    // save new list
    if let audios = audios {
      let restoreAudioList = NSEntityDescription.insertNewObject (
        forEntityName: entityName,
        into: context
      ) as! RestoreAudioList
      restoreAudioList.audioIDs = audios.map {
        "\($0.id)"
      }.joined(separator: ",")
      restoreAudioList.name = name
      restoreAudioList.type = type.rawValue
      if let currentUser = UserManager.shared.currentUser {
        restoreAudioList.userID = Int16(currentUser.identifier)
      } else {
        restoreAudioList.userID = -1
      }
      restoreAudioList.nowPlayingAlbumID = Int16(nowPlayingAlbumID)
      restoreAudioList.nowPlayingAudioID = Int16(nowPlayingAudioID)
      restoreAudioList.refID = refID
      
      do {
        try context.save()
      } catch let error {
        throw error
      }
    }
  }
  
  static func remove() throws {
    let request = NSFetchRequest<RestoreAudioList>()
    let entity = NSEntityDescription.entity(forEntityName: entityName, in: context)
    request.entity = entity
    if let currentUser = UserManager.shared.currentUser {
      request.predicate = NSPredicate(format: "userID = \(currentUser.identifier)")
    } else {
      request.predicate = NSPredicate(format: "userID = \(-1)")
    }
    do {
      if let currentList = try context.fetch(request).first {
        context.delete(currentList)
        try context.save()
      }
    } catch let error {
      throw error
    }
  }
}
